﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Pvf.Core.Tests
{
    public static class FieldCatcher
    {

        private static bool WriteAny;

        private static Dictionary<int, string> Input;

        public static bool CanPush() => Input != null;

        public static void Begin()
        {
            Input = new Dictionary<int, string>();
        }

        public static void Push(int key, string value)
        {
            if (Input == null)
            {
                throw new ArgumentNullException("请先执行Begin");
            }

            //throw new KeyNotFoundException($"{key}-{value}");
            Input[key] = value;

            WriteAny = true;
        }

        public static void Clear(TextWriter writer)
        {
            if (Input == null)
            {
                throw new ArgumentNullException("请先执行Begin");
            }

            foreach (var value in Input)
            {
                writer.WriteLine($"{value.Key}\t{value.Value}");
            }

            Clear();
        }

        public static void Clear()
        {
            Input = null;
            WriteAny = false;
        }

        public static void Clear(string saveTo)
        {
            if (Any())
            {
                using (var fs = new FileStream(saveTo, FileMode.Create, FileAccess.Write))
                {
                    using (var writer = new StreamWriter(fs))
                    {
                        Clear(writer);
                    }
                }
            }
            else
            {
                Clear();
            }
        }

        public static bool Any()
        {
            return WriteAny;
        }
    }
}
